{% extends 'base.html' %}
{% load static %}

{% block title %}消息中心{% endblock %}

{% block content %}
<div class="row">
    <!-- 侧边栏（保持不变） -->
    <div class="col-md-3 col-lg-2 sidebar p-3">
        <div class="list-group">
            <a href="{% url 'dashboard' %}" class="list-group-item list-group-item-action" data-target="content-dashboard">仪表盘</a>
            <a href="{% url 'user_manage' %}" class="list-group-item list-group-item-action">用户管理</a>
            <a href="{% url 'content_manage' %}" class="list-group-item list-group-item-action">内容管理</a>
            <a href="{% url 'system_config' %}" class="list-group-item list-group-item-action">系统配置</a>
            <a href="{% url 'data_statistics' %}" class="list-group-item list-group-item-action">数据统计</a>
            <a href="{% url 'log_manage' %}" class="list-group-item list-group-item-action">日志管理</a>
            <a href="{% url 'message_center' %}" class="list-group-item list-group-item-action active">消息中心</a>
            <a href="{% url 'help_document' %}" class="list-group-item list-group-item-action">帮助文档</a>
        </div>
    </div>

    <!-- 内容区域 -->
    <div class="col-md-9 col-lg-10 p-4">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-xl font-bold text-gray-800">消息中心</h3>
            <div class="flex space-x-3">
                <button id="mark-all-read" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition-all flex items-center">
                    <i class="fa fa-check-circle mr-2"></i> 全部标为已读
                </button>
                <div class="relative">
                    <button id="message-filter-btn" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition-all flex items-center">
                        <i class="fa fa-filter mr-2"></i> 筛选 <i class="fa fa-chevron-down ml-1"></i>
                    </button>
                    <div id="message-filter-dropdown" class="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg py-1 hidden z-10">
                        <a href="#" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" data-filter="all">全部消息</a>
                        <a href="#" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" data-filter="unread">未读消息</a>
                        <a href="#" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" data-filter="system">系统通知</a>
                        <a href="#" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" data-filter="user">用户消息</a>
                        <a href="#" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" data-filter="reminder">业务提醒</a>
                    </div>
                </div>
            </div>
        </div>

        <!-- 搜索栏 -->
        <div class="relative mb-4">
            <input type="text" id="message-search" placeholder="搜索消息..."
                   class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary outline-none transition-all">
            <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
        </div>

        <!-- 消息列表 -->
        <div class="bg-white rounded-lg shadow-sm overflow-hidden" id="message-list">
            <!-- 消息将由JavaScript动态生成 -->
        </div>

        <!-- 分页 -->
        <div class="mt-4 flex justify-between items-center">
            <div class="text-sm text-gray-500">
                显示 1-10 条，共 36 条
            </div>
            <div class="flex space-x-1">
                <button class="px-3 py-1 rounded border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">上一页</button>
                <button class="px-3 py-1 rounded border border-primary bg-primary text-sm font-medium text-white">1</button>
                <button class="px-3 py-1 rounded border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">2</button>
                <button class="px-3 py-1 rounded border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">3</button>
                <button class="px-3 py-1 rounded border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">下一页</button>
            </div>
        </div>
    </div>
</div>

<!-- 消息详情模态框 -->
<div id="message-detail-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full mx-4 overflow-hidden transform transition-all max-h-[90vh] flex flex-col">
        <div class="px-6 py-4 border-b border-gray-200 flex justify-between items-center">
            <h3 class="text-lg font-medium text-gray-900" id="modal-message-title">消息详情</h3>
            <button id="close-message-modal" class="text-gray-400 hover:text-gray-500 focus:outline-none">
                <i class="fa fa-times"></i>
            </button>
        </div>
        <div class="px-6 py-4 overflow-y-auto" id="message-modal-content">
            <!-- 消息内容将由JavaScript动态生成 -->
        </div>
        <div class="px-6 py-4 bg-gray-50 flex justify-end">
            <button id="close-message" class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                关闭
            </button>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 模拟消息数据
    const messages = [
        {
            id: 1,
            type: 'system',
            title: '系统更新提醒',
            content: '我们将于2024年6月10日进行系统维护和更新，届时系统将暂停服务2小时，请提前做好准备。',
            sender: '系统管理员',
            time: '2024-06-01 09:00',
            status: 'unread'
        },
        {
            id: 2,
            type: 'user',
            title: '用户反馈回复',
            content: '感谢您对我们系统的反馈，关于您提到的问题，我们已经记录并将在下次更新中进行优化。',
            sender: '客服',
            time: '2024-05-31 16:30',
            status: 'read'
        },
        {
            id: 3,
            type: 'reminder',
            title: '任务截止提醒',
            content: '您有一个任务"系统数据整理"将于2024年6月5日到期，请及时完成。',
            sender: '系统',
            time: '2024-05-30 14:15',
            status: 'unread'
        },
        {
            id: 4,
            type: 'system',
            title: '安全公告',
            content: '近期发现多起网络钓鱼事件，请不要轻易点击不明链接，如有疑问请联系系统管理员。',
            sender: '安全团队',
            time: '2024-05-29 10:20',
            status: 'read'
        },
        {
            id: 5,
            type: 'user',
            title: '新用户注册通知',
            content: '新用户"testuser"已成功注册，账号需要审核后才能使用。',
            sender: '系统',
            time: '2024-05-28 09:45',
            status: 'unread'
        },
        {
            id: 6,
            type: 'reminder',
            title: '订阅续费提醒',
            content: '您的高级会员将于2024年6月15日到期，请及时续费以保持服务。',
            sender: '财务系统',
            time: '2024-05-27 16:10',
            status: 'read'
        },
        {
            id: 7,
            type: 'system',
            title: '功能更新通知',
            content: '我们已更新了数据统计功能，新增了用户活跃度分析和内容类型分布图表，欢迎使用。',
            sender: '开发团队',
            time: '2024-05-26 11:30',
            status: 'read'
        },
        {
            id: 8,
            type: 'user',
            title: '关于系统问题的回复',
            content: '您好，关于您反馈的登录问题，我们已经排查并修复，请尝试重新登录。',
            sender: '技术支持',
            time: '2024-05-25 09:20',
            status: 'unread'
        },
        {
            id: 9,
            type: 'reminder',
            title: '待审批内容提醒',
            content: '目前有5条内容等待您的审批，请登录系统进行处理。',
            sender: '内容管理系统',
            time: '2024-05-24 14:45',
            status: 'read'
        },
        {
            id: 10,
            type: 'system',
            title: '服务条款更新',
            content: '我们已更新了服务条款，请在登录后查看并确认。',
            sender: '法务团队',
            time: '2024-05-23 16:00',
            status: 'unread'
        }
    ];

    // 渲染消息列表
    function renderMessageList(filteredMessages) {
        const messageList = document.getElementById('message-list');
        messageList.innerHTML = '';

        if (filteredMessages.length === 0) {
            messageList.innerHTML = `
                <div class="p-6 text-center">
                    <div class="flex justify-center mb-4">
                        <i class="fa fa-inbox text-gray-300 text-5xl"></i>
                    </div>
                    <h3 class="text-lg font-medium text-gray-900 mb-1">暂无消息</h3>
                    <p class="text-sm text-gray-500">您的消息列表是空的</p>
                </div>
            `;
            return;
        }

        filteredMessages.forEach(message => {
            // 设置消息类型图标和颜色
            let typeIcon, typeColor;
            switch(message.type) {
                case 'system':
                    typeIcon = 'fa-bullhorn';
                    typeColor = 'text-blue-500';
                    break;
                case 'user':
                    typeIcon = 'fa-envelope';
                    typeColor = 'text-indigo-500';
                    break;
                case 'reminder':
                    typeIcon = 'fa-bell';
                    typeColor = 'text-amber-500';
                    break;
                default:
                    typeIcon = 'fa-info-circle';
                    typeColor = 'text-gray-500';
            }

            // 设置消息状态样式
            const isUnread = message.status === 'unread';
            const messageClass = isUnread ? 'border-l-4 border-primary bg-blue-50 hover:bg-blue-100' : 'border-l-4 border-transparent hover:bg-gray-50';

            const messageElement = document.createElement('div');
            messageElement.className = `border-b border-gray-200 ${messageClass} transition-colors duration-200 cursor-pointer`;
            messageElement.setAttribute('data-id', message.id);

            messageElement.innerHTML = `
                <div class="flex items-start p-4">
                    <div class="flex-shrink-0 mr-4">
                        <div class="h-10 w-10 rounded-full bg-gray-100 flex items-center justify-center ${typeColor}">
                            <i class="fa ${typeIcon}"></i>
                        </div>
                    </div>
                    <div class="flex-1 min-w-0">
                        <div class="flex justify-between items-start">
                            <h3 class="text-sm font-medium text-gray-900 truncate">${message.title}</h3>
                            ${isUnread ? '<span class="bg-primary text-white text-xs font-semibold px-2 py-0.5 rounded">未读</span>' : ''}
                        </div>
                        <p class="mt-1 text-sm text-gray-500 line-clamp-2">${message.content}</p>
                        <div class="mt-2 flex justify-between items-center">
                            <p class="text-xs text-gray-500">
                                <span class="font-medium">${message.sender}</span> · ${message.time}
                            </p>
                            <div class="flex space-x-2">
                                <button class="text-gray-400 hover:text-gray-600 view-message" data-id="${message.id}">
                                    <i class="fa fa-eye"></i>
                                </button>
                                <button class="text-gray-400 hover:text-gray-600 mark-read" data-id="${message.id}" ${isUnread ? '' : 'hidden'}>
                                    <i class="fa fa-check-circle"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;

            messageList.appendChild(messageElement);
        });

        // 添加查看消息事件
        document.querySelectorAll('.view-message').forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                const messageId = parseInt(this.getAttribute('data-id'));
                viewMessage(messageId);
            });
        });

        // 添加标记为已读事件
        document.querySelectorAll('.mark-read').forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                const messageId = parseInt(this.getAttribute('data-id'));
                markMessageAsRead(messageId);
            });
        });

        // 添加点击消息查看详情事件
        document.querySelectorAll('#message-list > div').forEach(item => {
            item.addEventListener('click', function() {
                const messageId = parseInt(this.getAttribute('data-id'));
                viewMessage(messageId);
            });
        });
    }

    // 查看消息详情
    function viewMessage(messageId) {
        const message = messages.find(msg => msg.id === messageId);
        if (!message) return;

        // 设置消息类型图标和颜色
        let typeIcon, typeColor;
        switch(message.type) {
            case 'system':
                typeIcon = 'fa-bullhorn';
                typeColor = 'text-blue-500';
                break;
            case 'user':
                typeIcon = 'fa-envelope';
                typeColor = 'text-indigo-500';
                break;
            case 'reminder':
                typeIcon = 'fa-bell';
                typeColor = 'text-amber-500';
                break;
            default:
                typeIcon = 'fa-info-circle';
                typeColor = 'text-gray-500';
        }

        // 更新模态框内容
        document.getElementById('modal-message-title').textContent = message.title;

        const modalContent = document.getElementById('message-modal-content');
        modalContent.innerHTML = `
            <div class="flex items-start mb-4">
                <div class="flex-shrink-0 mr-4">
                    <div class="h-12 w-12 rounded-full bg-gray-100 flex items-center justify-center ${typeColor}">
                        <i class="fa ${typeIcon} text-xl"></i>
                    </div>
                </div>
                <div>
                    <h4 class="text-sm font-medium text-gray-900">${message.title}</h4>
                    <p class="mt-1 text-xs text-gray-500">
                        <span class="font-medium">${message.sender}</span> · ${message.time}
                    </p>
                </div>
            </div>
            <div class="border-t border-gray-200 pt-4">
                <p class="text-base text-gray-700 leading-relaxed">
                    ${message.content}
                </p>
            </div>
        `;

        // 显示模态框
        document.getElementById('message-detail-modal').classList.remove('hidden');

        // 如果是未读消息，标记为已读
        if (message.status === 'unread') {
            markMessageAsRead(messageId);
        }
    }

    // 标记消息为已读
    function markMessageAsRead(messageId) {
        const message = messages.find(msg => msg.id === messageId);
        if (!message || message.status === 'read') return;

        message.status = 'read';

        // 更新消息列表
        const currentFilter = document.querySelector('#message-filter-dropdown a.active')?.getAttribute('data-filter') || 'all';
        const filteredMessages = filterMessages(currentFilter);
        renderMessageList(filteredMessages);
    }

    // 标记所有消息为已读
    document.getElementById('mark-all-read').addEventListener('click', function() {
        messages.forEach(message => {
            if (message.status === 'unread') {
                message.status = 'read';
            }
        });

        // 更新消息列表
        const currentFilter = document.querySelector('#message-filter-dropdown a.active')?.getAttribute('data-filter') || 'all';
        const filteredMessages = filterMessages(currentFilter);
        renderMessageList(filteredMessages);

        alert('所有消息已标记为已读');
    });

    // 筛选消息
    function filterMessages(filterType) {
        switch(filterType) {
            case 'unread':
                return messages.filter(msg => msg.status === 'unread');
            case 'system':
                return messages.filter(msg => msg.type === 'system');
            case 'user':
                return messages.filter(msg => msg.type === 'user');
            case 'reminder':
                return messages.filter(msg => msg.type === 'reminder');
            default:
                return messages;
        }
    }

    // 筛选下拉菜单
    const filterBtn = document.getElementById('message-filter-btn');
    const filterDropdown = document.getElementById('message-filter-dropdown');

    filterBtn.addEventListener('click', function(e) {
        e.stopPropagation();
        filterDropdown.classList.toggle('hidden');
    });

    document.querySelectorAll('#message-filter-dropdown a').forEach(option => {
        option.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();

            // 更新选中状态
            document.querySelectorAll('#message-filter-dropdown a').forEach(a => {
                a.classList.remove('active', 'bg-gray-100');
            });
            this.classList.add('active', 'bg-gray-100');

            // 更新按钮文本
            const filterText = this.textContent;
            filterBtn.innerHTML = `<i class="fa fa-filter mr-2"></i> ${filterText} <i class="fa fa-chevron-down ml-1"></i>`;

            // 筛选消息
            const filterType = this.getAttribute('data-filter');
            const filteredMessages = filterMessages(filterType);
            renderMessageList(filteredMessages);

            // 关闭下拉菜单
            filterDropdown.classList.add('hidden');
        });
    });

    // 点击外部关闭下拉菜单
    document.addEventListener('click', function() {
        filterDropdown.classList.add('hidden');
    });

    // 关闭模态框
    document.getElementById('close-message-modal').addEventListener('click', function() {
        document.getElementById('message-detail-modal').classList.add('hidden');
    });

    document.getElementById('close-message').addEventListener('click', function() {
        document.getElementById('message-detail-modal').classList.add('hidden');
    });

    // 搜索消息
    const searchInput = document.getElementById('message-search');
    searchInput.addEventListener('input', function() {
        const searchTerm = this.value.toLowerCase().trim();
        if (!searchTerm) {
            // 如果搜索框为空，使用当前筛选条件
            const currentFilter = document.querySelector('#message-filter-dropdown a.active')?.getAttribute('data-filter') || 'all';
            const filteredMessages = filterMessages(currentFilter);
            renderMessageList(filteredMessages);
            return;
        }

        // 搜索消息
        const searchResults = messages.filter(msg =>
            msg.title.toLowerCase().includes(searchTerm) ||
            msg.content.toLowerCase().includes(searchTerm) ||
            msg.sender.toLowerCase().includes(searchTerm)
        );

        renderMessageList(searchResults);
    });

    // 初始化页面
    renderMessageList(messages);
});
</script>
{% endblock %}

{% block extra_js %}
<script>
    // 侧边栏交互逻辑
    document.querySelectorAll('.list-group-item').forEach(item => {
        item.addEventListener('click', function(e) {
            document.querySelector('.list-group-item.active').classList.remove('active');
            this.classList.add('active');
        });
    });
</script>
{% endblock %}